//
//  TYHLoginManager.m
//  OpenPractice
//
//  Created by tanyuehong on 7/7/18.
//  Copyright © 2018年  lijinghua. All rights reserved.
//


NSString *const kLoginNotification  = @"LoginNotification";
NSString *const kLogoutNotification = @"LogOutNotification";

#define TYH_USERTRY_LOGINPHONENUM  @"tyh_usertry_loginPhoneNum"

#import "TYHLoginManager.h"


@interface TYHLoginManager ()

@property (nonatomic, copy) NSString *token;
@property (nonatomic, strong) NSTimer *verifyTimer;
@property (nonatomic, strong) TYHUserEntity *currentUser;
@property (nonatomic, copy) smsSecodCount secodCountblock;
@property (nonatomic, assign) NSInteger verifyCodeCountdown;            //验证码倒计时
@property (nonatomic, strong) NSString *phoneNumberCountdown;           //正在倒计时的手机号

@end

@implementation TYHLoginManager

- (instancetype)init {
    self = [super init];
    if (self) {
        [self loadTYHUserEntity];
    }
    return self;
}

- (void)loadTYHUserEntity{
    TYHUserEntity *user = [[TYHUserEntity alloc] init];
    self.currentUser = user;
}

- (BOOL)checkUserPhoneNumSendSms:(NSString *)phone secondBlock:(void (^)(NSInteger secondCount))block {
    if (![phone isEqualToString:self.phoneNumberCountdown]|| self.verifyCodeCountdown==0) {
        if (block) {
            self.secodCountblock = block;
        }
        self.verifyCodeCountdown = 6;
        if (self.verifyTimer) {
            [self.verifyTimer invalidate];
            self.verifyTimer = nil;
        }
        __weak typeof(self) weakSelf = self;
        self.verifyTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:weakSelf selector:@selector(verifySmsCountdownWithTimer) userInfo:nil repeats:YES];
        return YES;
    }
    if (block) {
        self.secodCountblock = block;
    }
    return NO;
}

- (void)verifySmsCountdownWithTimer {
    self.verifyCodeCountdown--;
    if (self.secodCountblock) {
        self.secodCountblock(self.verifyCodeCountdown);
    }
    if (self.verifyCodeCountdown<= 0) {
        [self.verifyTimer invalidate];
        self.verifyTimer = nil;
        self.verifyCodeCountdown = 0;
        self.phoneNumberCountdown = nil;
    }
}

- (void)dealLoginSucess:(NSDictionary *)UserData {
    TYHUserEntity *loginUer = [TYHUserEntity yy_modelWithJSON:UserData];
    self.currentUser = loginUer;
}

- (void)regiserWithPhoneCode:(NSString *)phoneNum code:(NSString *)code zone:(NSString *)zone compeletBlock:(completeBlock)block {
    NSMutableDictionary *parmdict = [NSMutableDictionary dictionary];
    [parmdict setObject:phoneNum forKey:@"email"];
    [parmdict setObject:code forKey:@"phonecode"];
    [parmdict setObject:zone forKey:@"zone"];
    [TYHHTTPFacade doHttpRequest:@"https://www.redskt.com/api/users/regiserWithCode" parms:parmdict completeBlock:^(NSError *error, id resultObject) {
        if (!error && [resultObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *userData = [resultObject objectForKey:@"userData"];
            if (userData) {
                [self dealLoginSucess:userData];
            }
        }
        if (block) {
            block(error,resultObject);
        }
    }];
}

- (void)loginWithPhoneNum:(NSString *)phoneNum passWd:(NSString *)passWd compeletBlock:(completeBlock)block {
    [TYHHTTPFacade doHttpRequest:@"https://www.redskt.com/api/ucenter/login" parms: @{@"username":phoneNum,@"password":passWd,@"pageKey":@"84BHUR7vVxb/RYkmnyK+22WYD7G3toH8aCFavLS9lANn6ZCVXV+Q2YqBKrFXu8uovjtAjCrWbWL3aK1cH4W0mA==",@"verCode":@""} completeBlock:^(NSError *error, NSDictionary *data) {
        if (!error) {
            NSString *token = [data objectForKey:@"token"];
            if(!token || token.length == 0) {
                NSError *myError = [NSError errorWithDomain:NSURLErrorDomain code:601 userInfo:@{NSLocalizedDescriptionKey:@"token为空"}];
                if (block) {
                    block(myError,data);
                }
            } else {
                [self getUserInfo:token block:block];
            }
            return ;
        }
        if (block) {
            block(error,data);
        }
    }];
}

- (void)getUserInfo:(NSString *)token block:(completeBlock)block {
    NSString *tokenParm = [NSString stringWithFormat:@"Bearer %@",token]; // 妥协服务端格式
    [TYHHTTPFacade doGetHttpRequest:@"https://www.redskt.com/api/ucenter/getUserInfo" parms:nil headers:@{@"Authorization":tokenParm} completeBlock:^(NSError *error, NSDictionary *data) {
        NSDictionary *user = [data objectForKey:@"userInfo"];
        if(!error && data) {
            self.currentUser = [TYHUserEntity yy_modelWithJSON:user];
            self.currentUser.token = token;
            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginNotification object:nil];
        }
        if(block) {
            block(error,data);
        }
    }];
}

- (void)checkPhoneNumberStatus:(NSString *)phoneNum compeletBlock:(completeBlock)block {
    [TYHHTTPFacade doHttpRequest:@"https://www.redskt.com/api/users/checkphone" parms:@{@"phoneNum":phoneNum}  completeBlock:^(NSError *error, NSDictionary *data) {
        if (block) {
            block(error,data);
        }
    }];
}

- (NSString *)getUserTryLoginPhoneNum {
    return  [[NSUserDefaults standardUserDefaults] objectForKey:TYH_USERTRY_LOGINPHONENUM];
    
}
- (void)setUserTryLoginPhoneNum:(NSString *)phoneNum {
    if (phoneNum.length>0) {
        [[NSUserDefaults standardUserDefaults] setObject:phoneNum forKey:TYH_USERTRY_LOGINPHONENUM];
    }
}

@end
